//微信登录示例
import {alertProxy} from "./AlertProxy";
import {Platform} from "react-native";
import * as WeChat from 'react-native-wechat'
import toast from "./ToastProxy";
import {apiUrl} from "../../config";

interface AccessCallBack {
    (code: string): void
}

export async function wechatInstallCheck(): Promise<boolean> {
    return await WeChat.isWXAppInstalled();
}

export function WechatLogin(callback: AccessCallBack) {
    let scope = 'snsapi_userinfo';
    let state = 'wechat_sdk_demo';
    //判断微信是否安装
    WeChat.isWXAppInstalled()
        .then((isInstalled) => {
            if (isInstalled) {
                //发送授权请求
                WeChat.sendAuthRequest(scope, state)
                    .then(responseCode => {
                        console.log(responseCode);
                        //返回code码，通过code获取access_token
                        callback(responseCode.code);
                    })
                    .catch(err => {
                        toast("登录授权发生错误");
                        // alertProxy('登录授权发生错误：', err.message, [
                        //     {text: '确定'}
                        // ]);
                    })
            }
            // else {
            //     Platform.OS == 'ios' ?
            //         alertProxy('没有安装微信', '是否安装微信？', [
            //             {text: '取消'},
            //             {text: '确定', onPress: () => this.installWechat()}
            //         ]) :
            //         alertProxy('没有安装微信', '请先安装微信客户端在进行登录', [
            //             {text: '确定'}
            //         ])
            // }
        })
};

export async function WechatShare(userId: number, callback?: AccessCallBack) {
    try {
        await WeChat.shareToSession({
            type: 'news',
            title: '傻粮商城',
            thumbImage: "http://static.shanjiezhifu.com/xxx/xx/APPtubiao3.png",
            description: '您的朋友想要邀请您一起加入傻粮商城！',
            mediaTagName: 'email signature',
            webpageUrl: `${apiUrl}share?userId=${userId}`
        });
        toast("分享成功,快通知朋友下单吧~")
    } catch (e) {
        toast("已取消分享")
    }

}
